﻿using UnityEngine;
using System.Collections;

public class Shot : MonoBehaviour {

	public GameObject bulletContainer;
	public AudioSource source;
	public AudioClip shotSound;
	public AudioClip reloadSound;
	public GameObject reloadSprite;
	public ParticleSystem shotParticleSystem;

	private float reloadTimer;
	private int ammo = 6;
	private GameObject[] bullets;
	// Use this for initialization
	void Start () {
		reloadTimer = 3.0f;
		bullets = new GameObject[6];
		int index = 0;
		foreach (Transform child in bulletContainer.transform) {
			bullets[index] = child.gameObject;
			index ++;
		}
		shotParticleSystem.Stop ();
	}
	
	// Update is called once per frame
	void Update () {
		if (!Trigger.canShoot) {
			if (reloadTimer < 0f ) {
				reloadTimer = 3.0f;
				Trigger.canShoot = true;
				reloadSprite.GetComponent<SpriteRenderer>().enabled = false;
				if(ammo == 0) { 
					foreach (Transform child in bulletContainer.transform) {
						child.GetComponent<SpriteRenderer>().enabled = true;
					}
					source.PlayOneShot (reloadSound);
					reloadTimer = 2.0f;
					ammo = 6;
				}
			} else 
				reloadTimer -= Time.deltaTime;
		} else {
			if (Input.GetMouseButtonDown (0)) {

				Trigger.canShoot = false;
				ammo--;
				if(ammo==0) 
					reloadSprite.GetComponent<SpriteRenderer>().enabled = true;
				bullets[ammo].GetComponent<SpriteRenderer>().enabled = false;
				//reload między strzałami trwa 3 sekundy
				reloadTimer = 3.0f;
				source.PlayOneShot (shotSound);
				shotParticleSystem.Play ();

			}
		}
	}
}
